<template>
    <el-form ref="ruleFormRef" style="max-width: 600px;" :model="ruleForm" :rules="rules" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item  label="用户名" prop="AccountName">
            <el-input v-model="ruleForm.AccountName" />
        </el-form-item>
        <el-form-item label="密码" prop="AccountPass">
            <el-input v-model="ruleForm.AccountPass" type="password" />
        </el-form-item>
        <el-form-item label="验证码" prop="vcode">
            <el-input v-model="ruleForm.vcode" style="width: 120px;margin-right: 18px;" />
            <el-tag style="width: 80px; height:32px;cursor: pointer;" @click="setYcode"
             type="primary">{{ ycodeEx }}</el-tag>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                登录
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
            <el-button @click="getForest()">获取天气</el-button>
        </el-form-item>
    </el-form>
</template>
<style lang="css" scoped>
.el-form-item__label {
    color:aliceblue
}
</style>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { type ComponentSize, type FormInstance, type FormRules, ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import router from '@/router';

interface RuleForm {
    AccountName: string
    AccountPass: string
    vcode: string
}

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    AccountName: '',
    AccountPass: '',
    vcode: ''//用户输入的验证码
})


let ycode = ref(0)//验证码的计算结果
let ycodeEx = ref('')//展示的验证码表达式
const setYcode = () => {//计算验证码值的方法
    let num1 = Math.floor(Math.random() * 10)//第一个正整数
    let num2 = Math.floor(Math.random() * 10)//第一个正整数
    let op = Math.floor(Math.random() * 4)// 0 1 2 3
    if (op == 1) {//加法
        ycode.value = num1 + num2;
        ycodeEx.value = '' + num1 + '+' + num2 + '=?'
    } else if (op == 2) {
        if (num1 < num2) {
            let temp = num2;
            num2 = num1;
            num1 = temp;
        }
        ycode.value = num1 - num2;
        ycodeEx.value = '' + num1 + '-' + num2 + '=?'
    } else if (op == 3) {
        ycode.value = num1 * num2;
        ycodeEx.value = '' + num1 + 'x' + num2 + '=?'
    } else if (op == 0) {
        if (num2 == 0) {
            num2 = 1;
        }
        num1 = num2 * num1;
        ycode.value = num1 / num2;
        ycodeEx.value = '' + num1 + '÷' + num2 + '=?'
    }
}

const rules = reactive<FormRules<RuleForm>>({
    AccountName: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 15, message: '用户名长度必须是3-15', trigger: 'blur' },
    ],
    AccountPass: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 12, message: '密码长度必须是 6到12', trigger: 'blur' },
    ], vcode: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
    ],

})

const submitForm = async (formEl: FormInstance | undefined) => {

    if (ruleForm.vcode !== ycode.value.toString()) {
        //
        ElMessage.error('请填写正确的验证码.');
        return;
    }

    if (!formEl) return


    axios.get('http://localhost:5071/api/Account/Login', { params: { AccountName: ruleForm.AccountName, AccountPass: ruleForm.AccountPass } })
        .then((res) => {
            console.log(res.data.msg);
            // let token = sessionStorage.getItem('token')
            if (res.data.code == 201) {
                sessionStorage.setItem("jwttoken", res.data.msg)
                sessionStorage.setItem("loginName",ruleForm.AccountName);
                ElMessageBox.alert('登录成功');
                 // 登录成功，写JWT的 token到本地
        window.localStorage.setItem("token", res.data.data);
        // 数据提交后端要加入新的Token值
        axios.defaults.headers.common["Authorization"] =
            "Bearer " + res.data.data;
                router.push('/main');
            } else {
                ElMessageBox.alert(res.data.msg);
            }
        })

  
}

const getForest = () => {
    let token = sessionStorage.getItem('jwttoken') ?? '';
    axios.defaults.headers.common['Authorization'] = token;
    axios.get('http://localhost:5071/WeatherForecast').then(function (res) {
        alert(res.data[0].date)
    }).catch(err => {
        if (err.response.status === 401) {
            ElMessageBox.alert("您无权访问资源");
        }
    })

}
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))

onMounted(() => {
    setYcode();
});
</script>